package com.sky.service.impl;

import com.github.pagehelper.PageHelper;
import com.sky.dto.SalesTop10DTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Consumer;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 统计指定时间的营业额
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO TurnoverReport(LocalDate begin, LocalDate end) {
        List<LocalDate> datalist = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datalist.add(begin);
        }
        List<Double> turnoverList = new ArrayList<>();
        //查询每个日期对应的营业额
        for (LocalDate localDate : datalist) {
            //根据日期查询营业额
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //select sum(amount) from orders where order_time > beginTime and status = 5;
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("begin", beginTime);
            hashMap.put("end", endTime);
            hashMap.put("status", Orders.COMPLETED);
            Double d = ordersMapper.getByMap(hashMap);
            Double turnover = (d == null) ? 0.0 : d;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(datalist, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO UserReport(LocalDate begin, LocalDate end) {
        List<LocalDate> datalist = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datalist.add(begin);
        }

        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        for (LocalDate localDate : datalist) {
            //根据日期查询营业额
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("end", endTime);
            Integer totalNum = userMapper.getByTime(hashMap);
            hashMap.put("begin", beginTime);
            Integer newNum = userMapper.getByTime(hashMap);
            totalUserList.add(totalNum);
            newUserList.add(newNum);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(datalist, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO OrderReport(LocalDate begin, LocalDate end) {
        List<LocalDate> datalist = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datalist.add(begin);
        }
        List<Integer> validOrderCountList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        for (LocalDate localDate : datalist) {
            //根据日期查询营业额
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("end", endTime);
            hashMap.put("begin", beginTime);
            Integer orderNum = ordersMapper.getCountByMap(hashMap);
            orderCountList.add(orderNum);

            totalOrderCount += orderNum;
            //已完成的
            hashMap.put("status", Orders.COMPLETED);
            Integer completedOrderNum = ordersMapper.getCountByMap(hashMap);
            validOrderCountList.add(completedOrderNum);
            validOrderCount += completedOrderNum;
        }

        Double v = 0.0;
        if (totalOrderCount != 0) {
            v = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(datalist, ","))//日期
                .totalOrderCount(totalOrderCount)//总订单数
                .orderCompletionRate(v)//完成订单率
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))//每日完成订单数
                .orderCountList(StringUtils.join(orderCountList, ","))//每日订单数
                .validOrderCount(validOrderCount)//完成订单总数
                .build();
    }

    /**
     * 销量数据统计
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO SalesTop10Report(LocalDate begin, LocalDate end) {
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();


        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put("begin", beginTime);
        hashMap.put("end", endTime);
        hashMap.put("status", Orders.COMPLETED);

        PageHelper.startPage(1,10);
        List<SalesTop10DTO> list = orderDetailMapper.getByMap(hashMap);
        for (SalesTop10DTO salesTop10DTO : list) {
            nameList.add(salesTop10DTO.getName());
            numberList.add(salesTop10DTO.getNumber());
        }
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        //查询数据库
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //POI转为Excel
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //填充数据
        XSSFWorkbook excel = new XSSFWorkbook(stream);
        XSSFSheet sheet = excel.getSheet("sheet1");
        //第一行：时间
        sheet.getRow(1).getCell(1).setCellValue("时间："+begin+"至"+end);
        //第四行
        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessDataVO.getTurnover());
        row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessDataVO.getNewUsers());

        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
        //填充闽西数据
        LocalDate nowDay = begin;
        for (int i = 0; i < 30; i++) {
            nowDay = nowDay.plusDays(1);
            BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(nowDay, LocalTime.MIN), LocalDateTime.of(nowDay, LocalTime.MAX));
            row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(nowDay.toString());
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(3).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData.getUnitPrice());
            row.getCell(6).setCellValue(businessData.getNewUsers());
        }

        //用输出流输出到浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);
        outputStream.close();
        excel.close();
    }
}
